﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LCL;
using LCL.Caching;
using LCL.Config;
using LCL.RedisCache.Config;
using ServiceStack.Redis;

namespace LCL.RedisCache
{
    public class RedisCacheProvider : ICacheProvider
    {
        public RedisCacheProvider()
        {
            var conf= RedisConfigs.GetConfig();
            if (conf==null||!conf.ApplyRedis) {
                throw new Exception("redis没有启用，请检查配置");
            }
        }
        public static IRedisClient GetRedisClient()
        {
            return RedisManager.GetClient();
        }
        public T Get<T>(string key)
        {
            try
            {
                using (var client = GetRedisClient())
                {
                    return client.Get<T>(key);
                }
            }
            catch
            {
                return default(T);
            }
        }
        public void Set(string key, object data, int cacheTime)
        {
            try
            {
                using (var client = GetRedisClient())
                {
                    client.Set<object>(key, data, TimeSpan.FromMinutes(cacheTime));
                }
            }
            catch
            {
               
            }
        }
        public bool Exists(string key)
        {
            try
            {
                using (var client = GetRedisClient())
                {
                   return client.ContainsKey(key);
                }
            }
            catch
            {
                return false;
            }
        }
        public void Remove(string key)
        {
            try
            {
                using (var client = GetRedisClient())
                {
                    client.Remove(key);
                }
            }
            catch
            {
               
            }
        }
        public void RemoveByPattern(string pattern)
        {
            try
            {
                using (var client = GetRedisClient())
                {
                    var keys = client.GetKeysByPattern(pattern);
                    client.RemoveAll(keys);
                }
            }
            catch
            {

            }
        }
        public void Clear()
        {
            try
            {
                using (var client = GetRedisClient())
                {
                    var keys = client.GetAllKeys();
                    client.RemoveAll(keys);
                }
            }
            catch
            {

            }
        }

        protected int _timeOut = 3600;
        public virtual int TimeOut
        {
            set { _timeOut = value > 0 ? value : 3600; }
            get { return _timeOut > 0 ? _timeOut : 3600; }
        }
    }
}
